﻿#pragma warning(disable:4996)
#pragma warning(disable:4819)
#include "NodeAgentManger.hpp"
#include "cybertron/core/UtilString.hpp"
#include "NodeCommanderManger.hpp"
#include "cybertron/node/StartupArguments.hpp"
#include "TheApp.hpp"

NodeAgentManger::NodeAgentManger()
{
	zeroMembers();
}

NodeAgentManger::~NodeAgentManger()
{
	clear();
}

void NodeAgentManger::zeroMembers()
{
	// do nothing.
}

void NodeAgentManger::clear()
{
	{
		//std::unique_lock<std::recursive_mutex> lock(mMutex);
		//mTrafficNode = NULL;
		//mNodes.clear();
		//mNodeIdAllocator.clear();
	}

	zeroMembers();
}

int NodeAgentManger::AddAgentNode(NodeInfo* pNodeInfo)
{
	std::unique_lock<std::recursive_mutex> lock(mAgentMapLock);
	mAgentSocketMap[pNodeInfo->pSocket] = (*pNodeInfo);
	mAgentIdMap[pNodeInfo->nodeId] = (*pNodeInfo);
	CommanderNodeManger::GetInstance().dispatchAgentStatusChange(pNodeInfo->nodeId, Common::EAgentStatusOnline);
	return 0;
}

void NodeAgentManger::RemoveAgentNode(string agent_id)
{
	
	WorkNodeManger::GetInstance().RemoveNodeListByAgentId(agent_id);

	std::unique_lock<std::recursive_mutex> lock(mAgentMapLock);
	auto it = mAgentIdMap.find(agent_id);
	SocketBasePtr pSocket = 0;
	if (it != mAgentIdMap.end()) {
		pSocket = it->second.pSocket;
		mAgentIdMap.erase(it);
	}
	
	auto it2 = mAgentSocketMap.find(pSocket);
	if (it2 != mAgentSocketMap.end()) {
		mAgentSocketMap.erase(it2);
	}
	CommanderNodeManger::GetInstance().dispatchAgentStatusChange(agent_id, Common::EAgentStatusOffline);
	return;
}
NodeInfo* NodeAgentManger::GetAgentInfo(string agent_id) {
	std::unique_lock<std::recursive_mutex> lock(mAgentMapLock);
	auto it = mAgentIdMap.find(agent_id);

	if (it != mAgentIdMap.end()) {
		
		return &it->second;
	}
	return 0;
}
bool NodeAgentManger::IsHasAgentFree() {
	bool ret = false;
	std::unique_lock<std::recursive_mutex> lock(mAgentMapLock); 	

	for (auto it = mAgentIdMap.begin(); it != mAgentIdMap.end(); it++)
	{
		WorkNodeInfoList workList;
		WorkNodeManger::GetInstance().GetWorkListByAgentId(it->first, workList);
		bool bFind = true;
		for (size_t i = 0; i < workList.size(); i++)
		{
			if (workList[i]->mStatus != Common::EWorkNodeStatusFree) {
				bFind = false;
				break;
			}
		}
		if (bFind) {
			ret = true;
		}
		//agent_info_list.push_back(it->second);
	}
	return ret;
}
bool NodeAgentManger::GetAgentList(vector<NodeInfo>& agent_info_list) {
	std::unique_lock<std::recursive_mutex> lock(mAgentMapLock);
	for (auto it= mAgentIdMap.begin(); it!= mAgentIdMap.end(); it++)
	{
		agent_info_list.push_back(it->second);
	}
	return true;
}
int NodeAgentManger::GetAgentCount() {
	std::unique_lock<std::recursive_mutex> lock(mAgentMapLock);
	return int(mAgentIdMap.size());
}
void NodeAgentManger::SyncWorkNodes(string AgentId, Master::SyncWorkNodeListFromAgent syncWorkNodes) {

}

